package com.suray.socket.system.netty.client;

import com.suray.basic.wcs.utils.LoggerType;
import com.suray.basic.wcs.utils.ModuleType;
import com.suray.basic.wcs.utils.WcsFuncUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

@ChannelHandler.Sharable//1.标记这个类的实例可以在 channel 里共享
public class EchoClientHandler extends SimpleChannelInboundHandler<ByteBuf> {

    private EchoClient client;

    public EchoClientHandler(EchoClient client) {
        this.client = client;
    }

    /**
     * 上线
     *
     * @param ctx
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) {
//        ctx.writeAndFlush(Unpooled.copiedBuffer("Netty rocks!", //2.当被通知该 channel 是活动的时候就发送信息
//                CharsetUtil.UTF_8));
        client.setCtx(ctx);
    }

//    /**
//     * 收到数据
//     * @param ctx
//     * @param in
//     * @throws Exception
//     */
//    @Override
//    public void channelRead(ChannelHandlerContext ctx, Object in) throws Exception {
//        ByteBuf compBuf = (ByteBuf) in;
//        int len = compBuf.readableBytes();
//        byte[] arr = new byte[len];
//        if(!compBuf.hasArray()){
//            compBuf.getBytes(0, arr);
//        }
//        System.out.println("Client received: " + in.toString());//3.打印接收到的信息
//        ctx.writeAndFlush(in);
//    }

    /**
     * 收到数据
     *
     * @param ctx
     * @param in
     * @throws Exception
     */
    @Override
    public void channelRead0(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
        byte[] data = new byte[in.readableBytes()];
        try {
            in.readBytes(data);
        } catch (Exception e) {
            WcsFuncUtil.exceptionLog(ModuleType.SOCKET, LoggerType.INFO, 0, null, e, this.getClass());
        }
        client.addMessage(data);
    }

    /**
     * 异常
     *
     * @param ctx
     * @param cause
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        WcsFuncUtil.exceptionLog(cause, this.getClass());
        ctx.close();//5.关闭通道
    }

    /**
     * 服务器加入
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
    }

    /**
     * 服务器离开
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        client.setCtx(null);
    }

    /**
     * 掉线
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        client.setCtx(null);
    }
}
